package com.example.assetmanagement.service.impl;

import com.example.assetmanagement.common.PageRequest;
import com.example.assetmanagement.common.PageResponse;
import com.example.assetmanagement.domain.Category;
import com.example.assetmanagement.mapper.CategoryMapper;
import com.example.assetmanagement.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    public PageResponse<Category> list(PageRequest pageRequest, String name) {
        List<Category> list = categoryMapper.selectPage(pageRequest.getOffset(), pageRequest.getSize(), name);
        long total = categoryMapper.count(name);
        return new PageResponse<>(total, list);
    }

    @Override
    public List<Category> tree() {
        List<Category> all = categoryMapper.selectAll();
        // 构造简单树结构（父子关系）
        return buildTree(all, null);
    }

    private List<Category> buildTree(List<Category> nodes, Long parentId) {
        List<Category> children = new ArrayList<>();
        for (Category node : nodes) {
            if ((parentId == null && node.getParentId() == null) || (parentId != null && parentId.equals(node.getParentId()))) {
                List<Category> sub = buildTree(nodes, node.getId());
                // 若需要将 children 设置进对象，可在 Category 中添加 List<Category> children 字段
                // 此处简单返回扁平结果或实现自己 TreeVO
                children.add(node);
                children.addAll(sub);
            }
        }
        return children;
    }

    @Override
    public Category getById(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    @Transactional
    public void add(Category category) {
        categoryMapper.insert(category);
    }

    @Override
    @Transactional
    public void update(Long id, Category category) {
        category.setId(id);
        categoryMapper.update(category);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        try {
            categoryMapper.deleteById(id);
        } catch (Exception ex) {
            // MySQL 外键约束异常错误码 1451
            if (ex.getMessage() != null && ex.getMessage().contains("Cannot delete or update a parent row")) {
                throw new RuntimeException("分类下仍存在资产，无法删除");
            }
            throw ex;
        }
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        categoryMapper.deleteBatch(ids);
    }

    @Override
    public List<Category> listAll() {
        return categoryMapper.selectAll();
    }
} 